<!-- 卖家---整体营业额销量统计页面 -->
<template>
  <div class="container">
    <!-- *************************************搜索区************************************* -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <!-- 时间选择 -->
      <el-form-item>
        <el-switch
          @change="(type) => (queryParams.time = setStatisticsDefautTime(type))"
          v-model="queryParams.dateMark"
          active-color="#13ce66"
          inactive-color="#409eff"
          active-text="日"
          :active-value="'day'"
          inactive-text="月"
          :inactive-value="'month'"
        >
        </el-switch>
      </el-form-item>
      <el-form-item v-show="queryParams.dateMark == 'month'">
        <el-date-picker
          style="width: 400px"
          :clearable="false"
          v-model="queryParams.time"
          @change="handleQuery"
          type="monthrange"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item v-show="queryParams.dateMark == 'day'">
        <el-date-picker
          style="width: 400px"
          :clearable="false"
          @change="handleQuery"
          v-model="queryParams.time"
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-select @change="handleQuery" v-model="queryParams.shopId" :placeholder="$t('店铺名称')" clearable>
          <el-option :label="item.name" :value="item.id" v-for="item in sellerShops" :key="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-switch
          style="border: 1px solid #dbdbdb; padding: 15px; border-radius: 3px"
          @change="handleExclude"
          v-model="queryParams.isExclude"
          :active-text="$t('排除线下店铺')"
          :inactive-text="$t('不排除线下店铺')"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          <!-- 搜索 -->
          {{ $t('搜索') }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="legends">
      <div
        :style="{
          'border-top-color': $randomColor(index + 1),
        }"
        v-for="(item, index) in legends"
        :key="index"
        class="legends-item"
      >
        <div class="legends-item-title">
          <div>{{ item.name }}</div>
          <div>
            <i
              :style="{
                color: item.isShow ? $randomColor(index + 1) : '#ccc',
              }"
              class="el-icon-view"
              @click="switchLine(item)"
            ></i>
          </div>
        </div>
        <div class="legends-item-value">
          <span style="color: red">￥</span>
          <span @click="handleShowChart(item)">{{ item.total | thousand }}</span>
        </div>
      </div>
    </div>
    <div class="chart" id="chart"></div>
    <SellerSaleChart
      :show.sync="sellerSaleChart.show"
      :formData="sellerSaleChart.formData"
      :title="chartTitle"
      :useThousand="sellerSaleChart.useThousand"
    />
    <SkuFee :show.sync="skuFee.show" :formData="skuFee.formData" />
  </div>
</template>

<script>
import { getSalesVolumeListByTurnover, getShopBySeller } from '@/api/statistics/overallTurnoverSeller'
import * as echarts from 'echarts'
import SellerSaleChart from '@/views/statistics/sellerSalePlatform/components/sellerSaleChart.vue'
import { checkPermi } from '@/utils/permission'
import SkuFee from './components/skuFee.vue'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'OverallTurnoverSeller',
  components: {
    SellerSaleChart,
    SkuFee,
  },
  data() {
    return {
      distrId: JSON.parse(localStorage.getItem('distr') || '{}').distrId,
      chartTitle: '',
      skuFee: {
        show: false,
        formData: {},
      },
      sellerSaleChart: {
        show: false,
        useThousand: false,
        formData: {},
      },
      myChart: null,
      chartData: [],
      legends: [
        { useThousand: true, type: '2', isShow: true, name: this.$t('营业额'), key: 'turnover', total: '' },
        { useThousand: false, type: 'skuFee', isShow: true, name: this.$t('sku费用'), key: 'skuFee', total: '' },
        { useThousand: true, type: '4', isShow: true, name: this.$t('快递费用'), key: 'deliveryFee', total: '' },
        { useThousand: true, type: '5', isShow: true, name: this.$t('捆包费用'), key: 'bundleFee', total: '' },
        { useThousand: true, type: '6', isShow: true, name: this.$t('手续费'), key: 'commission', total: '' },
        { useThousand: true, type: '7', isShow: true, name: this.$t('利润'), key: 'profit', total: '' },
      ],
      sellerShops: [],
      // 查询参数
      queryParams: {
        dateMark: 'day',
        time: [],
        // 是否排除线下店铺 0-否 1-是
        isExclude: 0,
      },
    }
  },
  async created() {
    this.queryParams.time = this.setStatisticsDefautTime(this.queryParams.dateMark)
    this.getList()
    getShopBySeller().then((res) => {
      this.sellerShops = res.data
    })
  },

  methods: {
    handleExclude(value) {
      console.log(`value ==>`, value)
      this.getList()
    },
    handleShowChart(data) {
      const flag = checkPermi(['distribution:distributor:getSalesVolumePlatformPie']) //无权限 返回

      if (!flag) return

      const { type, name, useThousand } = data
      this.chartTitle = name
      const formData = {
        type,
        distrId: this.distrId,
        time: this.queryParams.time,
        shopId: this.queryParams.shopId || 'null',
        isExclude: this.queryParams.isExclude,
      }
      if (type == 'skuFee') {
        this.skuFee.formData = formData
        this.skuFee.formData.shopId = this.queryParams.shopId
        this.skuFee.show = true
        return
      }

      this.sellerSaleChart.formData = formData
      this.sellerSaleChart.useThousand = useThousand
      this.sellerSaleChart.show = true
    },
    switchLine(data) {
      // const { name, key } = data
      // let series
      // if (data.isShow) {
      //   // 隐藏该折线
      //   series = [{ name, data: [] }]
      // } else {
      //   // 显示该折线
      //   series = [
      //     {
      //       name,
      //       data: this.chartData[key]?.map((i) => i.value),
      //     },
      //   ]
      // }
      // this.myChart.setOption({ series })
      data.isShow = !data.isShow
      this.drawCharts()
    },
    drawCharts() {
      const data = JSON.parse(JSON.stringify(this.chartData))
      var option = {
        // legend: {
        //   data: legends,
        // },
        color: this.legends.map((_, index) => this.$randomColor(index + 1)),
        tooltip: {
          trigger: 'axis',

          // axisPointer: {
          //   type: 'shadow',
          // },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.commission.map((i) => i.date),
        },
        dataZoom: [
          {
            type: 'slider', // 使用滑动条
            // xAxisIndex: [0], // 对第一个X轴（索引为0）应用数据区域缩放
            // start: 0, // 初始范围的起始值（0表示从头开始）
            // end: 100, // 初始范围的结束值（50表示初始显示前50%的数据）
          },
        ],
        grid: {
          right: 40,
          left: 40,
          bottom: 20,
          top: 10,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            fontSize: '12',
            formatter(v) {
              v = v.toString()
              if (v >= 100000000000) {
                return v.substring(0, 5) / 10 + '亿'
              } else if (v >= 10000000000) {
                return v.substring(0, 4) / 10 + '亿'
              } else if (v >= 1000000000) {
                return v.substring(0, 3) / 10 + '亿'
              } else if (v >= 100000000) {
                return v.substring(0, 2) / 10 + '亿'
              } else if (v >= 10000000) {
                return v.substring(0, 4) + '万'
              } else if (v >= 1000000) {
                return v.substring(0, 3) + '万'
              } else if (v >= 100000) {
                return v.substring(0, 2) + '万'
              } else if (v >= 10000) {
                return v.substring(0, 2) / 10 + '万'
              } else if (v >= 1000) {
                return Math.floor(v / 1000) + '千'
              } else {
                return v
              }
            },
          },
        },
        series: this.legends.map((item, index) => {
          return {
            name: item.name,
            type: 'line',
            data: item.isShow ? data[item.key]?.map((i) => i.value) : [],
            // smooth: true,
          }
        }),
      }

      const chartDom = document.getElementById('chart')

      this.myChart = echarts.getInstanceByDom(chartDom)

      if (this.myChart == null) {
        this.myChart = echarts.init(chartDom)
      }
      this.myChart.setOption(option)
      //图形宽度随屏幕宽度改变而改变
      window.onresize = this.myChart.resize
    },

    getList() {
      /****************** 处理查询条件 *********************/
      const selectDate = this.queryParams.time || []
      const startTime = selectDate[0] || ''
      const endTime = selectDate[1] || ''
      const data = {
        ...this.queryParams,
        startTime,
        endTime,
      }
      delete data.time
      /**************** 处理查询条件 end *******************/
      getSalesVolumeListByTurnover(data).then((res) => {
        this.legends.map((item) => {
          item.total = (+res.data[item.key + 'Total'])?.toFixed() || 0
        })
        this.chartData = res.data
        this.drawCharts()
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.value1 = null
      Object.keys(this.queryParams).forEach((key) => {
        this.queryParams[key] = null
      })
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10

      this.getList()
    },
  },
}
</script>
<style lang="scss" scoped>
.container {
  min-height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 20px 40px;
  .legends {
    display: flex;
    gap: 5px;
    &-item {
      padding: 15px;
      padding-bottom: 30px;
      flex: 1;
      border: 1px solid #ccc;
      border-radius: 3px;
      border-top-width: 2px;
      &-title {
        font-weight: bold;
        font-size: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        i {
          cursor: pointer;
          //color: #ccc;
          font-size: 20px;
          &:hover {
            color: #1890ff;
          }
        }
      }
      &-value {
        cursor: pointer;
        font-weight: bold;
        margin-top: 15px;
        font-size: 17px;
        &:hover {
          color: #1890ff;
        }
      }
    }
  }
  .chart {
    width: 100%;
    height: calc(100vh - 300px);
    //border: 2px solid #bababa;
    padding: 15px;
    border-radius: 8px;
  }
}
</style>
